package com.example.book.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.book.entity.User;
import com.example.book.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ryl
 * @since 2021-05-05
 */
@Controller
@RequestMapping("/book/user")
public class UserController {


    @Autowired
    UserService userService;

    @RequestMapping("/registerUser")
    public String registerUser(User user, Model model){
        boolean save = userService.save(user);
        model.addAttribute("res",save);
        return "pages/user/regist_result";
    }



    @RequestMapping("/loginUser")
    public String loginUser(User user, Model model, HttpServletRequest request){
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper
                .select("password")
                .eq("username",user.getUsername());

        List<User> list = userService.list(queryWrapper);
        if(!list.isEmpty()){
            String password = user.getPassword();
            if(password.equals(list.get(0).getPassword())){
                HttpSession session = request.getSession();
                session.setAttribute("user",user);
                model.addAttribute("res",true);
            }
        }
        else{
            model.addAttribute("res",false);
        }

        return "pages/user/login_result";


    }





}

